package com.ad.pet.app.serach;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.Logger;
import com.ad.pet.MainActivity;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.serach.adapter.SearchHotAdapter;
import com.ad.pet.app.serach.adapter.SerachKeyWordAdapter;
import com.ad.pet.common.data.utils.DensityUtil;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.BaseActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.Amzon;
import com.ad.pet.models.remote.KeyWord;
import com.ad.pet.models.remote.mall.SearchEndGood;
import com.ad.pet.ui.SimpleDividerDecoration;
import com.ad.pet.utils.LyxUtils;
import com.library.flowlayout.FlowLayoutManager;
import com.library.flowlayout.SpaceItemDecoration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * Created by SEELE on 2018/3/28.
 */

public class SerachHistoryActivity extends BaseActivity implements SerachHistoryContract.View {
    @BindView(R.id.mDeleteImg)
    ImageView mMDeleteImg;
    @BindView(R.id.mTypeInput)
    EditText mMTypeInput;
    @BindView(R.id.ll_serach)
    LinearLayout mLlSerach;

    @BindView(R.id.tv_clear)
    TextView mTvClear;
    @BindView(R.id.recycler_history)
    RecyclerView mRecyclerHistory;

    @BindView(R.id.activity_main_search)
    LinearLayout mActivityMainSearch;
    @Inject
    SerachHistoryPresenter mSerachHistoryPresenter;
    @BindView(R.id.recycler_type)
    RecyclerView recyclerType;
    private List<KeyWord> hirstoryList;


    private SerachKeyWordAdapter mMHirstoryAdapter;

    @BindView(R.id.iv_back)
    ImageView ivBack;

    private CustomPopupWindow mPop;
    private SearchHotAdapter mSearchHotAdapter;

    @Inject
    RxDisposable mRxDisposable;

    @BindView(R.id.recycler_hot)
    RecyclerView mRecyclerViewHot;

    @BindView(R.id.tv_change)
    TextView mTvChange;

    private SerachKeyWordAdapter mRecommedAdapter;
    private SerachKeyWordAdapter mTypeAdapter;


    @Override
    protected void initViews() {
//        mSerachHistoryPresenter.onCreate(this);
//        mSerachHistoryPresenter.getKeyword();
        mSerachHistoryPresenter.onCreate(this);
        initPop();
    }

    @Override
    protected void initData() {


        String history = SpUtil.getInstance().getString(Constant.HISTORY_MAIN, "[]");
        hirstoryList = new Gson().fromJson(history, new TypeToken<List<KeyWord>>() {
        }.getType());

        mMHirstoryAdapter = new SerachKeyWordAdapter(hirstoryList);


        FlowLayoutManager flowLayoutManager = new FlowLayoutManager();
        mRecyclerHistory.addItemDecoration(new SpaceItemDecoration(DensityUtil.dip2px(5)));
        mRecyclerHistory.setLayoutManager(flowLayoutManager);
        mRecyclerHistory.setAdapter(mMHirstoryAdapter);
        mMHirstoryAdapter.bindToRecyclerView(mRecyclerHistory);
        mMHirstoryAdapter.setEmptyView(R.layout.layout_empty_noinfo);


        mRecommedAdapter = new SerachKeyWordAdapter(null);


        FlowLayoutManager flowLayoutManager1 = new FlowLayoutManager();
        mRecyclerViewHot.addItemDecoration(new SpaceItemDecoration(DensityUtil.dip2px(5)));
        mRecyclerViewHot.setLayoutManager(flowLayoutManager1);
        mRecyclerViewHot.setAdapter(mRecommedAdapter);


        FlowLayoutManager flowLayoutManager4 = new FlowLayoutManager();
        recyclerType.addItemDecoration(new SpaceItemDecoration(DensityUtil.dip2px(5)));
        recyclerType.setLayoutManager(flowLayoutManager4);
        mTypeAdapter = new SerachKeyWordAdapter(null);
        recyclerType.setAdapter(mTypeAdapter);

        mSerachHistoryPresenter.getKeyword();
        mSerachHistoryPresenter.getCateGoryWord();

    }

    @Override
    protected void initEvents() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mMTypeInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (TextUtils.isEmpty(mMTypeInput.getText().toString().trim())) {
                    ToastUtil.getToastUtil().showShort(getString(R.string.please_input_serach_content));
                    return false;
                }
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    addHistoryList(mMTypeInput.getText().toString());
                    Navigation.goSerachEnd(mActivity, mMTypeInput.getText().toString(), MainActivity.REQUEST_GO_MALL, "", "");
//                    }
                    return true;
                }
                return false;
            }
        });

        mRxDisposable.add(RxTextView.textChanges(mMTypeInput).subscribe(new Action1<CharSequence>() {
            @Override
            public void call(final CharSequence charSequence) {
                if (charSequence.length() > 0) {

                    mPop.showAtLocation(mLlSerach, Gravity.NO_GRAVITY, 0, LyxUtils.dp2px(mActivity, 95));

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getServiceInfo(charSequence.toString());

                        }
                    }).start();
                } else {
                    mPop.dismiss();
                }
            }
        }));

        mTvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSerachHistoryPresenter.getKeyword();
            }
        });

        mTvClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.createDialog(mActivity, getString(R.string.tips), getString(R.string.is_clear_hirstory), true, getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }, getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        SpUtil.getInstance().putString(Constant.HISTORY_MAIN, "[]");
                        hirstoryList.clear();
                        mMHirstoryAdapter.notifyDataSetChanged();
                        dialogInterface.dismiss();
                    }
                }).show();

            }
        });


        mMHirstoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mMHirstoryAdapter.getData() != null)
                    Navigation.goSerachEnd(mActivity, mMHirstoryAdapter.getData().get(position).getTitle(), MainActivity.REQUEST_GO_MALL, "", "");
            }
        });
        mMDeleteImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mMTypeInput.getText().toString().trim())) {
                    ToastUtil.getToastUtil().showShort(getString(R.string.please_input_serach_content));
                    return;
                }
                addHistoryList(mMTypeInput.getText().toString());
                Navigation.goSerachEnd(mActivity, mMTypeInput.getText().toString(), MainActivity.REQUEST_GO_MALL, "", "");
            }
        });


        mSearchHotAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Navigation.goSerachEnd(mActivity, mSearchHotAdapter.getData().get(position).getValue(), MainActivity.REQUEST_GO_MALL, mSearchHotAdapter.getData().get(position).getValue(), "");
            }
        });

        mRecommedAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Navigation.goSerachEnd(mActivity, mRecommedAdapter.getData().get(position).getTitle(), MainActivity.REQUEST_GO_MALL, "", "");
            }
        });

        mTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if ("0".equals(mTypeAdapter.getData().get(position).getCategory_id())) {
                    RxBus.getDefault().post("desinger_to");
                    finish();
                } else {
                    Navigation.goSerachEnd(mActivity, mTypeAdapter.getData().get(position).getName(), MainActivity.REQUEST_GO_MALL, mTypeAdapter.getData().get(position).getCategory_id(), "");
                }
            }
        });

    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_serach_hirstory;
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void getKeywordSuccess(List<KeyWord> commList) {


        mRecommedAdapter.setNewData(commList);


    }

    @Override
    public void getSearchEndSuccess(SearchEndGood searchEndGood) {

    }

    @Override
    public void getTypeWordSucceses(List<KeyWord> commList) {
        mTypeAdapter.setNewData(commList);
    }

    @Override
    public void getCateGoryWord(List<KeyWord> list) {
        mTypeAdapter.setNewData(list);
    }

    private boolean addHistoryList(String keyword) {
        if (TextUtils.isEmpty(keyword)) {
            ToastUtil.getToastUtil().showShort(getString(R.string.search));
            return true;
        }
        KeyWord label = new KeyWord();
        label.setTitle(keyword);
        if (!hirstoryList.contains(label)) {
            hirstoryList.add(label);

        } else {
            int i = hirstoryList.indexOf(label);
            if (i > 0) {
                hirstoryList.remove(i);
                hirstoryList.add(0, label);
            }
        }
        mMHirstoryAdapter.notifyDataSetChanged();
        SpUtil.getInstance().putString(Constant.HISTORY_MAIN, new Gson().toJson(hirstoryList));
        return false;
    }

    @Override
    protected boolean isStatusBarTransparent() {
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {
            case MainActivity.REQUEST_GO_MALL:
                setResult(RESULT_OK, data);
                finish();
                break;

        }
    }

    @Override
    protected void setContentViewBefore() {
        super.setContentViewBefore();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StatusBarCompat.setStatusBarColor(this, Color.parseColor("#0F0F33"), false);
        }

    }

    @Override
    public void error(int code, String msg) {

    }


    private void initPop() {
        mPop = new CustomPopupWindow.Builder(mActivity)
                .setContentView(R.layout.item_base_recycler)
                .setwidth(LinearLayout.LayoutParams.MATCH_PARENT)
                .setheight(LyxUtils.dp2px(mActivity, 400))
                .setBackgroundAlpha(1f)
                .build();
        RecyclerView searchLv = (RecyclerView) mPop.getItemView(R.id.recycler_view);
        searchLv.setLayoutManager(new LinearLayoutManager(mActivity));
        mSearchHotAdapter = new SearchHotAdapter(null);
        searchLv.addItemDecoration(new SimpleDividerDecoration(mActivity, 2, R.color.grey_ac));
        searchLv.setAdapter(mSearchHotAdapter);


    }


    @Override
    protected void onDestroy() {
        mRxDisposable.clear();
        mPop.dismiss();
        super.onDestroy();
    }

    public void getServiceInfo(String keyword) {
        String strResult = "https://completion.amazon.com/api/2017/suggestions?session-id=130-1198080-4771426&customer-id=&request-id=DXHXNDYQTS4ZEXZFTNVG&page-type=Gateway&lop=en_US&site-variant=desktop&client-info=amazon-search-ui&mid=ATVPDKIKX0DER&alias=aps&b2b=0&fresh=0&ks=83&prefix=%s&event=onKeyPress&limit=11&fb=1&suggestion-type=KEYWORD&suggestion-type=WIDGET&_=1558515814290";
        try {
            URL url = new URL(String.format(strResult, keyword));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setUseCaches(false);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            strResult = buffer.toString();

            Logger.e("strResult-->" + strResult);


            final String finalStrResult = strResult;
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Amzon gson = new Gson().fromJson(finalStrResult, Amzon.class);
                    mSearchHotAdapter.setNewData(gson.getSuggestions());
                }
            });


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
